package com.dongdongshop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.dongdongshop.mongopojo.Comment;
import com.dongdongshop.service.CommentService;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@DubboService
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    //判断集合是否存在
    @Override
    public void criteriaComment(){
        if (mongoTemplate.collectionExists("comments")){
//            mongoTemplate.dropCollection("comment");//删除集合
            mongoTemplate.dropCollection("comments");//添加创建集合
        }
        mongoTemplate.createCollection("comments");
        String simpleUUID = IdUtil.simpleUUID();
        //集合中添加数据
        Comment comments = new Comment(simpleUUID,1565464654L,"zhangsan", DateUtil.date(),"5","哈哈哈哈",0);
        mongoTemplate.insert(comments);
    }

    @Override
    public void addEvaluate(Comment comment) {
        comment.setId(IdUtil.simpleUUID());
        comment.setTime(new Date());
        comment.setLike(0);
        mongoTemplate.insert(comment);
    }

    //评论分页查询
    public List<Comment> pageFindComment(Integer pageNumber, Integer pageSize){
        Query query = new Query();
        query.skip(pageNumber).limit(pageSize);
        return mongoTemplate.find(query,Comment.class);
    }
    /*删除评论*/
    public boolean deleteComment(Long id){
        Query query = new Query(Criteria.where("id").is(id));
        DeleteResult remove = mongoTemplate.remove(query);
        return remove != null;
    }
    /*点赞*/
    public boolean likeComment(Long id){
        Query query = new Query(Criteria.where("id").is(id));//条件查询,然后修改
        Update update = new Update();
        update.inc("like");//自增1
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
        return true;
    }
}
